package com.example.demo.config;

import com.example.demo.aspect.ApiLogAspect;
import com.example.demo.aspect.LogTraceAspect;
import com.example.demo.event.ApiLogListener;
import com.example.demo.event.ErrorLogListener;
import com.example.demo.event.UsualLogListener;
import com.example.demo.filter.LogTraceFilter;
import com.example.demo.props.PropertySource;
import com.example.demo.props.RequestLogProperties;
import com.example.demo.service.ILogApiService;
import com.example.demo.service.ILogErrorService;
import com.example.demo.service.ILogUsualService;
import com.example.demo.util.SpringUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.servlet.DispatcherType;

/**
 * 日志工具自动配置
 *
 * @author cici
 */
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(RequestLogProperties.class)
//@PropertySource(value = "classpath:/test-log.yml")
public class LogToolAutoConfiguration {

	@Bean
	public ApiLogAspect apiLogAspect() {
		return new ApiLogAspect();
	}

	@Bean
	public LogTraceAspect logTraceAspect() {
		return new LogTraceAspect();
	}

	@Bean
	public SpringUtil getSpringUtil() {
		return new SpringUtil();
	}

	@Bean
	public FilterRegistrationBean<LogTraceFilter> logTraceFilterRegistration() {
		FilterRegistrationBean<LogTraceFilter> registration = new FilterRegistrationBean<>();
		registration.setDispatcherTypes(DispatcherType.REQUEST);
		registration.setFilter(new LogTraceFilter());
		registration.addUrlPatterns("/*");
		registration.setName("LogTraceFilter");
		registration.setOrder(Ordered.LOWEST_PRECEDENCE);
		return registration;
	}

	@Bean
	public ApiLogListener apiLogListener(ILogApiService logService) {
		return new ApiLogListener(logService);
	}

	@Bean
	public ErrorLogListener errorEventListener(ILogErrorService logService) {
		return new ErrorLogListener(logService);
	}

	@Bean
	public UsualLogListener usualEventListener(ILogUsualService logService) {
		return new UsualLogListener(logService);
	}

}
